'''
Created on 19.09.2012

@author: doleynik
'''
from google.appengine.api import users
from webapp2_extras import i18n

from apnetmodels.apnetusers import APNETUser

user_interface_lang = ''

def GetAPNETUser():
    user = users.get_current_user()
    au = APNETUser.get_by_key_name(user.email())
    if au:
        if au.state:
            if au.lang == 'en':
                locale = 'en_GB'
            elif au.lang == 'fr':
                locale = 'fr_FR'
            user_interface_lang = locale
            i18n.get_i18n().set_locale(locale)
            
            if not au.last_active_immeuble_id:
                for s in au.user_syndics.run():
                    for imm in s.syndic.imm_syndic_set.run():
                        au.last_active_immeuble_id = imm.key().id()
                        au.put()
            return au
    return None
        
def userstateformat(value):
    if value == True:
        return i18n.gettext('Active')
    else:
        return i18n.gettext('Inactive')

def datetimeformat(value, format='%d/%m/%Y'):
    return value.strftime(format)

def TrueFalseToYesNoFormat(value):
    if value == True:
        return i18n.gettext('Yes')
    else:
        return i18n.gettext('No')

def CurrencyFormat(value, format='{:,.2f}'):
    return "{:,.2f}".format(value)

def set_last_active_immeuble_id(imm_id):
    user = users.get_current_user()
    au = APNETUser.get_by_key_name(user.email())
    imm_id = long(imm_id)
    if au:
        au.last_active_immeuble_id = imm_id
        au.put()
    return True

def distinct(array):
    unique_results = []
    keys = []
    for obj in array:
        k = obj.key().id_or_name()
        if k not in keys:
            keys.append(k)
            unique_results.append(obj)

    return unique_results


